package cn.itcast.n4_共享模型_管程;

import cn.itcast.util.Sleeper;
import lombok.extern.slf4j.Slf4j;

import static cn.itcast.util.Sleeper.sleep;

@Slf4j(topic = "c.Test37_锁活跃性_死锁现象")
public class Test38_锁活跃性_死锁现象_哲学家就餐 {
    public static void main(String[] args) {
        Chopstick1 c1 = new Chopstick1("1");
        Chopstick1 c2 = new Chopstick1("2");
        Chopstick1 c3 = new Chopstick1("3");
        Chopstick1 c4 = new Chopstick1("4");
        Chopstick1 c5 = new Chopstick1("5");
        // 此时都是先拿左边，后拿右边
        new Philosopher1("苏格拉底", c1, c2).start();
        new Philosopher1("柏拉图", c2, c3).start();
        new Philosopher1("亚里士多德", c3, c4).start();
        new Philosopher1("赫拉克利特", c4, c5).start();
        new Philosopher1("阿基米德", c5, c1).start();
    }
}

/**
 * 哲学家类
 */
@Slf4j(topic = "c.Philosopher1")
class Philosopher1 extends Thread {
    Chopstick1 left;
    Chopstick1 right;

    public Philosopher1(String name, Chopstick1 left, Chopstick1 right) {
        super(name);
        this.left = left;
        this.right = right;
    }

    @Override
    public void run() {
        while (true) {
            //　尝试获得左手筷子
            synchronized (left) {
                // 尝试获得右手筷子
                synchronized (right) {
                    eat();
                }
                // 放下右手筷子
            }
            //　放下左手筷子
        }
    }

    private void eat() {
        log.debug("eating...");
        Sleeper.sleep(0.5);
    }
}

class Chopstick1 {
    String name;

    public Chopstick1(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "筷子{" + name + '}';
    }
}
